<template>
  <div class="login-form">
    <el-form :model="form" ref="formRef" label-width="80px" @submit.native.prevent="handleSubmit">
      <el-form-item label="用户名" prop="username" :rules="[{ required: true, message: '请输入用户名', trigger: 'blur' }]">
        <el-input v-model="form.username" placeholder="请输入用户名" />
      </el-form-item>

      <el-form-item label="密码" prop="password" :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]">
        <el-input type="password" v-model="form.password" placeholder="请输入密码" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleSubmit" :loading="loading">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useAuthStore } from '../store/index.ts';  // 引入 Pinia 的 store
import { ElForm, ElFormItem, ElInput, ElButton } from 'element-plus';
import { login } from '../api/services.ts';  // 登录接口

const form = ref({
  username: '',
  password: ''
});

const loading = ref(false);  // 登录时加载状态
const authStore = useAuthStore();  // 使用 Pinia store

const handleSubmit = async () => {
  if (!form.value.username || !form.value.password) {
    return;
  }

  loading.value = true;
  try {
    const response = await login(form.value.username, form.value.password);
    if (response.token) {
      authStore.setToken(response.token);  // 设置 token
      authStore.setUser(response.user);    // 设置用户信息
    }
  } catch (error) {
    console.error(error);
    alert('登录失败，请检查用户名和密码');
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.login-form {
  width: 400px;
  margin: 100px auto;
}
</style>
